package com.home766.util;

import org.apache.commons.codec.binary.Hex;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;

/**
 * 异或通联POS报文originalData 数据获取mac 值
 * xor originalData
 * @author sean
 */
public class XORUtil {
	public static void main(String[] args) throws UnsupportedEncodingException {
		String str= String.valueOf(new BigDecimal("100.00"));
//		String str="PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iR0JLIiA/PjxST09UPjxDX1RSQU5TQUNUSU9OX1RZUEU+MDEwMDwvQ19UUkFOU0FDVElPTl9UWVBFPjxDX0JBTktfVFlQRT4yMDY8L0NfQkFOS19UWVBFPjxDX0JBTktfQ09ERT5hbGxpbnBheTwvQ19CQU5LX0NPREU+PENfTUVSQ0hBTlRfQ09ERT44MjE1MTAxNjMwMDAwMTY8L0NfTUVSQ0hBTlRfQ09ERT48Q19NRVJDSEFOVF9OQU1FPlRlc3ROYW1lPC9DX01FUkNIQU5UX05BTUU+PENfUE9TX05PPjAwMjMwMDExPC9DX1BPU19OTz48Q19TRVJJQUxfTk8+MTA0MDEwMTAzMzEyMDE2MDAwNTExPC9DX1NFUklBTF9OTz48VF9UUkFOU0FDVElPTl9EQVRFPjIwMTYwMjAxMTcyODMzPC9UX1RSQU5TQUNUSU9OX0RBVEU+PENfTUFDPjEyMzQ1Njc4OTBBQkNERUY8L0NfTUFDPjwvUk9PVD4K";
//		byte[] data=str.getBytes("GBK");
//		System.out.println(data.length);
//		System.out.println(556/8);
//		System.out.println(java.util.Arrays.toString(byte2Int(data)));
		System.out.println(str.split("\\.")[0]);
	}
	public static String getMac(String str) throws UnsupportedEncodingException {
		byte[] data=str.getBytes("GBK");
		// 进行分组
		int group = (data.length + (8 - 1)) / 8;
		// 偏移量
		int offset = 0;
		// 输入计算数据
		byte[] edata = null;
		for (int i = 0; i < group; i++) {
			byte[] temp = new byte[8];
			if (i != group - 1) {
				System.arraycopy(data, offset, temp, 0, 8);
				offset += 8;
			} else {// 只有最后一组数据才进行填充0x00
				System.arraycopy(data, offset, temp, 0, data.length - offset);
			}

			if (i != 0) {// 只有第一次不做异或
				temp = XOR(edata, temp);
			}
			edata=temp;
		}
		String mac = Hex.encodeHexString(edata);
		System.out.println(mac);
		return mac;
	}
	
	private static int[] byte2Int(byte[] data) {
		int[] result = new int[data.length];

		for (int i = 0; i < data.length; i++) {
			if (data[i] < 0) {
				result[i] = data[i] + 256;
			} else {
				result[i] = data[i];
			}
		}

		return result;
	}
	
	/**
	 * 异或
	 * @param edata 结果数组
	 * @param temp 目标数组
	 * @return
	 */
	private static byte[] XOR(byte[] edata, byte[] temp) {
		byte[] result = new byte[8];
		for (int i = 0, j = result.length; i < j; i++) {
			result[i] = (byte) (edata[i] ^ temp[i]);
		}
		return result;
	}
}
